<template>
  <div class="product-list" v-loading="loading">
    <!--搜索表单-->
    <div class="common-seach-wrap">
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane :name="item.name" v-for="(item,cindex) in categoryList" :key="'tab-'+cindex">
          <span slot="label">{{item.name}} </span>
        </el-tab-pane>
      </el-tabs>
      <el-tabs v-model="activeNameTab" @tab-click="handleChildClick">
        <el-tab-pane :name="citem.name" v-for="(citem,dindex) in childcategoryList" :key="'chitab-'+dindex">
          <span slot="label">{{citem.name}} </span>
        </el-tab-pane>
      </el-tabs>
      <el-form size="small" :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item label="商品名称">
          <el-input size="small" v-model="searchForm.product_name" placeholder="请输入商品名称"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button size="small" type="primary" icon="el-icon-search" @click="onSubmit">查询</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!--内容-->
    <div class="product-content">
      <div class="table-wrap">
        <el-table size="small" :data="tableData" border style="width: 100%" v-loading="loading">
          <el-table-column prop="product_id" width="60" label="商品ID"></el-table-column>
          <el-table-column prop="product_name" label="产品" width="400px">
            <template slot-scope="scope">
              <div class="product-info">
                <div class="pic"><img v-img-url="scope.row.image[0].file_path" alt=""/></div>
                <div class="info">
                  <div class="name">{{ scope.row.product_name }}</div>
                  <div class="price">￥{{ scope.row.product_price }}</div>
                  <div class="price" v-if="scope.row.audit_status == 20">未通过原因：{{ scope.row.audit_remark }}</div>
                  <div class="price" v-if="scope.row.audit_status == 30">强制下架：{{ scope.row.audit_remark }}</div>
                </div>
              </div>
            </template>
          </el-table-column>

          <!-- <el-table-column prop="category.name" label="分类"></el-table-column> -->
          <el-table-column prop="category_name_text" label="分类"></el-table-column>
          <el-table-column label="现售价">
            <template slot-scope="scope">
              <div class="text-red">￥{{ Number(scope.row.product_price) + Number(scope.row.sell_product_price) }}</div>
            </template>
          </el-table-column>
          <el-table-column label="加价">
            <template slot-scope="scope">
              <div class="product-info-big">
                <el-input type="number" v-model="scope.row.sell_product_price" style="width: 100px;" :min="0" @change="onSaveMe(scope.row)"></el-input>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="显示状态" width="200px">
            <template slot-scope="scope">
              <div class="product-info-big">
                <el-switch
                  v-model="scope.row.is_show"
                  :active-value="1"
                  :inactive-value="0"
                  @change="()=>isShowFunc(scope.row)"
                  active-color="#13ce66"
                  inactive-color="#cccccc"
                ></el-switch>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <!--分页-->
    <div class="pagination">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        background
        :current-page="curPage"
        :page-size="pageSize"
        layout="total, prev, pager, next, jumper"
        :total="totalDataNumber"
      ></el-pagination>
    </div>

    <div class="common-button-wrapper">
      <el-button size="small" type="info" @click="cancelFunc">返 回</el-button>
      <!-- <el-button size="small" type="primary" @click="onSubmit" :disabled="save_loading">保存</el-button> -->
    </div>
  </div>
</template>

<script>
import PorductApi from '@/api/product.js';
import StallApi from "@/api/stall.js";
import { mapMutations } from "vuex";
import qs from 'qs';

export default {
  components: {
  },
  data() {
    return {
      /*切换菜单*/
      activeName: '',
      /*切换菜单*/
      activeNameTab: '',
      /*切换菜单ID*/
      activeNameTabId: 0,
      /*切换选中值*/
      activeIndex: '0',
      /*是否正在加载*/
      loading: true,
      /*是否正在提交保存*/
      save_loading: false,
      /*一页多少条*/
      pageSize: 20,
      /*一共多少条数据*/
      totalDataNumber: 0,
      /*当前是第几页*/
      curPage: 1,
      /*搜索参数*/
      searchForm: {
        product_name: '',
        category_id: ''
      },
      /*列表数据*/
      tableData: [],
      /*全部分类*/
      categoryList: [],
      childcategoryList: [],
      supplier: [],
      /*统计数据*/
      product_count: {},
      // 存储离开当前页时的tab
      pageCacheData: {},
      /*展示数据*/
      propsParam: {
        label: 'name',
        value: 'category_id',
        children: 'child',
        checkStrictly: true
      },
      parentsVal:[],
      stall_id: 0,
    };
  },
  created() {
    this.stall_id = this.$route.query.stall_id;
  },
  async mounted() {
    /*获取列表*/
    await this.getCategroyList();
    await this.getData();
  },

  beforeDestroy() {
    this.pageCacheData.activeName = this.activeName
    this.setProductManagementTab(this.pageCacheData)
  },
  methods: {
    ...mapMutations('pageTab', ['setProductManagementTab']),

    /*选择第几页*/
    handleCurrentChange(val) {
      let self = this;
      self.loading = true;
      self.curPage = val;
      self.getData();
    },

    /*每页多少条*/
    handleSizeChange(val) {
      this.pageSize = val;
      this.getData();
    },

    /*切换菜单*/
    handleClick(tab, event) {
      let childcategoryList = this.categoryList[tab.index];
      this.childcategoryList = childcategoryList.child;
    },

    /*切换菜单*/
    handleChildClick(tab, event) {
      let self = this;
      let category_list = self.childcategoryList[tab.index];
      self.activeNameTabId = category_list.category_id;
      self.curPage = 1;
      self.getData();
    },

    /*获取列表*/
    async getData(activeName) {
      let self = this;
      let Params = self.searchForm;
      Params.sid = self.stall_id;
      Params.page = self.curPage;
      Params.list_rows = self.pageSize;
      Params.category_id = self.activeNameTabId;
      self.loading = true;
      console.log(Params.category_id)
      try {
        const data = await StallApi.productList(Params, true);
        self.loading = false;
        self.tableData = data.data.list.data;
        self.totalDataNumber = data.data.list.total;
        self.product_count = data.data.product_count;
      } catch (error) {
        self.loading = false;
      }
    },

    async getCategroyList(){
      return new Promise(async (resolve, reject) => {
        let self = this;
        let Params = {id:this.stall_id};
        StallApi.stallcategory(Params, true)
          .then(async (data) => {
            self.categoryList = data.data.list;
            self.activeName = data.data.list[0].name;
            let childcategoryList = data.data.list[0].child;
            self.childcategoryList = childcategoryList;
            self.activeNameTab = childcategoryList[0].name;
            self.activeNameTabId = childcategoryList[0].category_id;
            // console.log(self.activeNameTabId)
            resolve('ok');
          }).catch(async (er) => {
            console.log('er');
            reject(er);
          });
      })
    },

    onSaveMe(e){
      let self = this;
      let sell_product_price = Number(e.sell_product_price)
      let Params = {};
      Params.stall_id = this.stall_id
      Params.product_id = e.product_id
      Params.product_price = sell_product_price
      Params.is_show = e.is_show

      self.save_loading = true;
      StallApi.changeProductStatus(Params, true)
        .then(data => {
          self.save_loading = false;
          // self.$message({
          //   message: '恭喜你，调整成功',
          //   type: 'success'
          // });
          // self.cancelFunc();
          // self.tableData = data.data.list;
          // self.categoryModel.catList = self.tableData;
          // self.category_count = data.data.category_count;
        })
        .catch(error => {
          self.save_loading = false;
        });
    },

    /*是否显示开关*/
    isShowFunc(e) {
      console.log(e.is_show)
      this.onSaveMe(e);
    },

    /*搜索查询*/
    onSubmit() {
      this.curPage = 1;
      this.getData();
    },

    /*打开添加*/
    addClick() {
      this.$router.push('/product/product/add');
    },

    /*打开编辑*/
    editClick(row) {
      this.$router.push({
        path: '/product/product/edit',
        query: {
          product_id: row.product_id,
          scene: 'edit'
        }
      });
    },

    /*打开复制*/
    copyClick(row) {
      this.$router.push({
        path: '/product/product/edit',
        query: {
          product_id: row.product_id,
          scene: 'copy'
        }
      });
    },

    /*删除*/
    delClick: function (row) {
      let self = this;
      let msg = '';
      if (row.product_status == 30) {
        msg = '删除后不可恢复，确认删除该记录吗?';
      } else {
        msg = '删除后将移动到回收站，确定删除该记录吗?';
      }
      self
        .$confirm(msg, '提示', {
          type: 'warning'
        })
        .then(() => {
          PorductApi.delProduct({
            product_id: row.product_id
          }).then(data => {
            self.$message({
              message: '删除成功',
              type: 'success'
            });
            self.getData();
          });
        });
    },
    /*修改状态*/
    changeStatus(item, value) {
      let self = this;
      let msg = '';
      if (value == 10) {
        msg = '确认要上架该商品吗?';
      } else {
        msg = '确认要下架该商品吗?';
        if (self.activeName == 'recovery') {
          msg = '确认要移动该商品到仓库吗?';
        }
      }
      self.$confirm(msg, '提示', {
        type: 'warning'
      })
        .then(() => {
          PorductApi.changeStatus({
            product_id: item.product_id,
            state: value
          }).then(data => {
            self.$message({
              message: '操作成功',
              type: 'success'
            });
            self.getData();
          });
        });
    },
    /*取消*/
    cancelFunc() {
      this.$router.back(-1);
    },
  }
};
</script>

<style>
.el-cascader-panel .el-radio {
  width: 100%;
  height: 100%;
  z-index: 10;
  position: absolute;
  top: 10px;
  right: 10px;
}
.el-cascader-panel .el-radio__input {
  visibility: hidden;
}
.el-cascader-panel .el-cascader-node__postfix {
  top: 10px;
}
.el-tabs__nav-wrap::after {
  height: 0 !important;
}
.pagination{
  margin-bottom: 50px;
}
.text-red{
  color: rgb(255, 51, 0);
}
</style>
